package com.classic.base;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.SyncStateContract;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.classic.content.contents;
import com.classic.dialog.ShardHintDialog;
import com.classic.duanzhi.DZDataBen1;
import com.classic.duanzhi.R;
import com.classic.duanzhi.UShardActivity;
import com.classic.utils.helper;
import com.qy.sdk.Datas.NativeObject;
import com.qy.sdk.Interfaces.RDInterface;
import com.qy.sdk.Utils.NativeModel;
import com.qy.sdk.rds.BannerView;
import com.qy.sdk.rds.NativeView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseListFragment extends LazyLoadFragment {
    private RefreshLayout refreshLayout;         //刷新控件
    private int pagerNumber = 1;                //当前页面数据页码
    private LinearLayout empty;                  //空页面布局
    private FrameLayout bannerContainer;                  //Banner

    private List<DZDataBen1> mListData = new ArrayList<>();// 当前页面总数据
    public boolean isRefresh = true;            //是否是在刷新中
    private CustomAdapter mAdapter;             //列表适配器
    private List<NativeObject> mAdViewList = new ArrayList<>();                  //保存广告数据

    @Override
    public void fetchData() {
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initView() {
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        ListView mRecyclerView = rootView.findViewById(R.id.listView);
        empty = rootView.findViewById(R.id.ll_empty);
        bannerContainer = rootView.findViewById(R.id.bannerContainer);

        mAdapter = new CustomAdapter();
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAdapter);
        //刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                initNativeExpressAD();
                initData(1);
            }
        });
        //加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                initData(pagerNumber + 1);
                int size = mAdViewList.size();
                int position = contents.FIRST_AD_POSITION + contents.ITEMS_PER_AD * (size - 2);
                int itemCount = mAdapter.getItemCount();
                if (position < itemCount) {
                    initNativeExpressAD();
                }
            }

        });
        addADBanner();
    }

    protected void addADBanner() {
        Log.d("------qy---------", "banner");
        BannerView ad = new BannerView();
        ad.setInterface(getActivity(), new RDInterface() {
            @Override
            public void rdView(ViewGroup benner) {
                super.rdView(benner);
                bannerContainer.addView(benner);//layout是你自己定义的布局
                System.out.println("-------qy------- 添加banner：");
            }

            @Override
            public void onError(String string) {
                super.onError(string);

                System.out.println("-------qy------- 添加banner：onError:" + string);
            }

            @Override
            public void onLoadSuccess() {
                super.onLoadSuccess();
                System.out.println("-------qy------- 添加banner：onLoadSuccess");
            }

            @Override
            public void onClose() {
                super.onClose();
                System.out.println("-------qy------- 添加banner：onClose");

            }
        });
        ad.load();
        ad.show();
    }

    @Override
    protected void initData() {

    }

    /**
     * @param number 页码
     * @return 请求接口
     */
    private String getUrl(String number) {
        return contents.url + getUrlInfo() + "/" + number + "/";
    }

    /**
     * 获取url关键字字段
     *
     * @return 接口关键字
     */
    protected abstract String getUrlInfo();

    /**
     * @param number 页码
     *               请求数据方法
     */
    void initData(final int number) {
        isRefresh = false;
        new Thread() {
            @Override
            public void run() {
                Document doc;
                try {
                    String url = getUrl(String.valueOf(number));
                    doc = Jsoup.connect(url).get();
                    Elements post = doc.getElementsByClass("post");
                    final List<DZDataBen1> dataBens = new ArrayList<>();
                    for (int i = 0; i < post.size(); i++) {
                        Element element = post.get(i);
                        element.text();
                        Elements elementsByClass = element.getElementsByClass("post-title");
                        Elements c = element.getElementsByClass("post-content");
                        Elements c1 = element.getElementsByClass("post-meta");
                        Log.d("---------------", c.text() + " ----- " + elementsByClass.text() + " ----- ");
                        DZDataBen1 dataBen = new DZDataBen1(elementsByClass.text(), c.text().replace(" ", "\n").replace(":\n", ": "), c1.text().split(" ")[0]);
                        dataBens.add(dataBen);
                    }
                    if (null == getActivity()) return;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pagerNumber = number;
                            if (pagerNumber == 1) {
                                mListData = dataBens;
                            } else {
                                mListData.addAll(dataBens);
                            }
                            if (dataBens.size() < 10) {
                                refreshLayout.setEnableLoadMore(false);
                                if (pagerNumber != 1) {
                                    showTT("没有更多了");
                                }
                            } else {
                                refreshLayout.setEnableLoadMore(true);
                            }
                            if (dataBens.size() == 0 && pagerNumber == 1) {
                                empty.setVisibility(View.VISIBLE);
                            } else {
                                empty.setVisibility(View.GONE);
                            }
                            mAdapter.setNotifyDataSetChanged();
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                            isRefresh = true;
                        }
                    });
                } catch (IOException e) {
                    if (getActivity() == null) return;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showTT("网络信号不好,请检查网络！");
                            mAdapter.setNotifyDataSetChanged();
                            if (pagerNumber == 1 && mListData.size() == 0) {
                                empty.setVisibility(View.VISIBLE);
                            } else {
                                empty.setVisibility(View.GONE);
                            }
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                            isRefresh = true;
                        }
                    });
                }
            }
        }.start();
    }

    ShardHintDialog dialog;

    private void showDialog() {
        if (null == dialog)
            dialog = new ShardHintDialog(getActivity());
        dialog.show();

    }

    private void dismissDialog() {
        if (null != dialog)
            dialog.dismiss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    /**
     * 请求广告
     */
    private void initNativeExpressAD() {

        //创建原生实例，原生模板为纯图
        NativeView nativeView = new NativeView(NativeModel.THREE_IMAGE);
//设置广告接口
        nativeView.setInterface(getActivity(), new RDInterface() {
            //获取元素列表
            @Override
            public void onNativeList(List<Object> list) { //实际返回广告数量
                Log.d("---------qy-------------", list.size() + "");
                ArrayList<NativeObject> objects = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    NativeObject nativeObject = NativeObject.create(list.get(i));
                    objects.add(nativeObject);
                }
                if (pagerNumber == 1) {
                    mAdViewList = objects;
                } else {
                    mAdViewList.addAll(objects);
                }
                if (!isRefresh) return;
                mAdapter.setNotifyDataSetChanged();
            }

            @Override
            public void onError(String string) {
                super.onError(string);
                Log.d("---------qy-------------ListError:", string + "");
            }

            @Override
            public void onLoadSuccess() {
                super.onLoadSuccess();
                Log.d("---------qy-------------onLoadSuccess:", "onLoadSuccess");
            }

            @Override
            public void onClose() {
                super.onClose();

                System.out.println("-------qy------- 原生list onClose：onClose");
            }
        });
//设置元素数量（可能返回0~指定数量)
        nativeView.load(10);


//        ADSize adSize = new ADSize(ADSize.FULL_WIDTH, ADSize.AUTO_HEIGHT); // 消息流中用AUTO_HEIGHT
//        NativeExpressAD mADManager = new NativeExpressAD(getActivity(), adSize, contents.id, contents.ids, this);
//        mADManager.loadAD(contents.AD_COUNT);
    }

    class CustomAdapter extends BaseAdapter {
        static final int TYPE_DATA = 0;
        static final int TYPE_AD = 1;
        private List<Object> mData = new ArrayList<>();

        public void setNotifyDataSetChanged() {
            mData = new ArrayList<>();
            mData.addAll(mListData);
            for (int i = 0; i < mAdViewList.size(); i++) {
                int position = contents.FIRST_AD_POSITION + contents.ITEMS_PER_AD * i;
                if (position < mData.size()) {
                    NativeObject view = mAdViewList.get(i);
                    if (position >= 0) {
                        mData.add(position, view);
                    }
                }
            }
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public int getItemViewType(int position) {
            return mData.get(position) instanceof NativeObject ? TYPE_AD : TYPE_DATA;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        public int getItemCount() {
            if (mData != null) {
                return mData.size();
            } else {
                return 0;
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (getItemViewType(position) == TYPE_AD) {
                NativeObject adView = (NativeObject) mData.get(position);
                View render = adView.render();
                return render;
            } else {
                View inflate = getLayoutInflater().inflate(R.layout.ad_item_anepisode_layout, parent, false);
                TextView time = inflate.findViewById(R.id.tv_time);
                TextView tvTitle = inflate.findViewById(R.id.tv_title);
                TextView week = inflate.findViewById(R.id.tv_week);
                final LinearLayout shard = inflate.findViewById(R.id.ll_shard_layout);
                TextView sub = inflate.findViewById(R.id.tv_subtitle);
                TextView tvDetails = inflate.findViewById(R.id.tv_details);
                final LinearLayout ll_shard = inflate.findViewById(R.id.ll_shard);
                TextView u_name = inflate.findViewById(R.id.u_name);
                ImageView u_logo = inflate.findViewById(R.id.u_logo);
                final DZDataBen1 o = (DZDataBen1) mData.get(position);
                time.setText(o.getDate());
                u_name.setText(contents.APPNAME);
                u_logo.setImageDrawable(contents.appLogo);
                tvDetails.setVisibility(View.VISIBLE);
                tvDetails.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        v.setVisibility(View.GONE);
                        ll_shard.setVisibility(View.VISIBLE);
                        showDialog();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDialog();
                                        Bitmap itemViewBitmap = getItemViewBitmap(shard);
                                        v.setVisibility(View.VISIBLE);
                                        ll_shard.setVisibility(View.GONE);

                                        Uri imageUri = Uri.parse(MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), itemViewBitmap, null, null));
                                        Intent shareIntent = new Intent();
                                        shareIntent.setAction(Intent.ACTION_SEND);
                                        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
                                        shareIntent.setType("image/*");
                                        getActivity().startActivityForResult(shareIntent,102);
                                    }
                                });
                            }
                        }, 500);
                    }
                });
                week.setText(helper.getWeek(o.getDate()));
                sub.setText(TextUtils.isEmpty(o.getContent()) ? o.getTitle() : o.getContent());
                tvTitle.setText(TextUtils.isEmpty(o.getContent()) ? o.getTitle() : o.getTitle());
                return inflate;
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(" ----- ,",requestCode+"requestCode"+ "   resultCode:"+resultCode );
    }

    /**
     * 截取scrollview的屏幕
     **/
    public static Bitmap getItemViewBitmap(LinearLayout scrollView) {
        int h = 0;
        Bitmap bitmap;
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;

    }


    /**
     //     * RecyclerView的Adapter
     //     */
//    class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
//
//        static final int TYPE_DATA = 0;
//        static final int TYPE_AD = 1;
//        private List<Object> mData = new ArrayList<>();
//        private List<View> ADData = new ArrayList<>();
//
//        CustomAdapter() {
//            this.mData = new ArrayList<>();
//            this.ADData = new ArrayList<>();
//        }
//
//        public void setNotifyDataSetChanged() {
//            mData = new ArrayList<>();
//            mData.addAll(mListData);
//            for (int i = 0; i < mAdViewList.size(); i++) {
//                int position = contents.FIRST_AD_POSITION + contents.ITEMS_PER_AD * i;
//                if (position < mData.size()) {
//                    NativeObject view = mAdViewList.get(i);
//                    if (position >= 0) {
//                        mData.add(position, view);
//                    }
//                }
//            }
//            notifyDataSetChanged();
//        }
//
//
//        @Override
//        public int getItemCount() {
//            if (mData != null) {
//                return mData.size();
//            } else {
//                return 0;
//            }
//        }
//
//        @Override
//        public int getItemViewType(int position) {
//            return mData.get(position) instanceof NativeObject ? TYPE_AD : TYPE_DATA;
//        }
//
//        @Override
//        public void onBindViewHolder(@NonNull final CustomAdapter.CustomViewHolder holder, final int position) {
//            int type = getItemViewType(position);
//            if (TYPE_AD == type) {
//                holder.container.removeAllViews();
//                NativeObject adView = (NativeObject) mData.get(position);
//                View render = adView.render();
//                if (holder.container.getChildCount() != 0 && holder.container.getChildAt(0) == render) {
//                    return;
//                }
//                if (holder.container.getChildCount() > 0) {
//                    holder.container.removeAllViews();
//                }
//                if (render.getParent() != null) {
//                    ((ViewGroup) render.getParent()).removeView(render);
//                }
//                holder.container.addView(render);
//            } else {
//                DZDataBen1 o = (DZDataBen1) mData.get(position);
//                holder.time.setText(o.getDate());
//                holder.week.setText(helper.getWeek(o.getDate()));
//                holder.sub.setText(TextUtils.isEmpty(o.getContent()) ? o.getTitle() : o.getContent());
//                holder.tvTitle.setText(TextUtils.isEmpty(o.getContent()) ? o.getTitle() : o.getTitle());
//            }
//        }
//
//        @NonNull
//        @Override
//        public CustomAdapter.CustomViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
////            int layoutId = (viewType == TYPE_AD) ? R.layout.ad_item_express_ad : R.layout.ad_item_anepisode_layout;
//            int layoutId = (viewType == TYPE_AD) ? R.layout.ad_item_express_ad : R.layout.ad_item_anepisode_layout;
//            View view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutId, null);
//            return new CustomViewHolder(view);
//        }
//
//        class CustomViewHolder extends RecyclerView.ViewHolder {
//            TextView title, week, sub, time, tvTitle;
//            public ViewGroup container;
//
//            CustomViewHolder(View view) {
//                super(view);
//                title = view.findViewById(R.id.title);
//                container = view.findViewById(R.id.express_ad_container);
//
//                time = view.findViewById(R.id.tv_time);
//                tvTitle = view.findViewById(R.id.tv_title);
//                week = view.findViewById(R.id.tv_week);
//                sub = view.findViewById(R.id.tv_subtitle);
//            }
//        }
//    }


}
